package dto

import (
	"encoding/json"
	"server-admin-api/global"
	"server-admin-api/models"
	"server-admin-api/views"
)

type CustomizeDto struct {

}

func NewCustomizeDto() *CustomizeDto {
	return &CustomizeDto{}
}

func (c *CustomizeDto) Count(param views.CustomizePageVo) (int64, error) {
	var count int64
	err := global.DB.
		Model(&models.Customize{}).
		Where("group_id = ?", param.GroupId).
		Count(&count).
		Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

func (c *CustomizeDto) Finds(param views.CustomizePageVo) ([]models.Customize, error) {
	var data []models.Customize
	tx := global.DB.
		Order("run_time desc").
		Limit(param.Size).
		Offset((param.Page - 1) * param.Size).
		Where("group_id = ?", param.GroupId)
	if param.Title != "" {
		tx = tx.Where("title like %?%", param.Title)
	}
	if err := tx.Find(&data).Error; err != nil {
		return nil, err
	}
	return data, nil
}

func (c *CustomizeDto) FindOne(id int) (models.Customize, error) {
	var data models.Customize
	if err := global.DB.Where("id = ?", id).First(&data).Error; err != nil {
		return models.Customize{}, err
	}
	return data, nil
}


func (c *CustomizeDto) Insert(data models.Customize) error {
	return global.DB.Create(&data).Error
}

func (c *CustomizeDto) Update(id int, data views.CustomizeCreate) error {
	var m map[string]interface{}
	b, _ := json.Marshal(&data)
	_ = json.Unmarshal(b, &m)
	return global.DB.Model(&models.Customize{}).Where("id = ?", id).Updates(m).Error
}

func (c *CustomizeDto) DeleteOne(id int) error {
	return global.DB.Delete(&models.Customize{}, id).Error
}
